package com.lagou.edu.controller;

import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailServiceFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/code")
//@RefreshScope
public class CodeController {

    @Autowired
    private CodeService codeService;
    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @GetMapping("/create/{email}")
    @HystrixCommand(
            commandProperties = {
                    // 每一个属性都是一个HystrixProperty
                    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1000")
            },
            fallbackMethod = "myFallBack"  // 回退方法
    )
    public int create(@PathVariable String email){
        String code = String.valueOf(getRandomNum());

        int state = codeService.create(email, code);
        if(state == 0){
            // 发送邮件
            try{
                boolean sendEmail = emailServiceFeignClient.sendEmail(email, code);
                System.out.println("发送邮件详情："+ sendEmail);
                if(sendEmail){
                    return 0;
                }
                return 7;
            }catch (Exception e){
                return 5;
            }
        }
        return state;
    }

    @GetMapping("/validate/{email}/{code}")
    public int validate(@PathVariable String email, @PathVariable String code){
        return codeService.validate(email, code);
    }

    /**
     * 随机生成六位数验证码
     * @return
     */
    public int getRandomNum(){
        Random r = new Random();
        return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
    }

    /*
        定义回退方法，返回预设默认值
        注意：该方法形参和返回值与原始方法保持一致
     */
    public int myFallBack(String email) {
        return 6; // 兜底数据
    }

}
